package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Mylinja 2021-12-15 星期三 10:53
 */
@Slf4j
@WebFilter("/*")
public class LoginCheckFilter implements Filter {
    /**
     * 路径匹配器，支持通配符
     */
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    /**
     * 拦截方法，前置拦截和后置拦截都在此方法中完成
     *
     * @param servletRequest  域请求对象
     * @param servletResponse 域响应对象
     * @param filterChain     啥玩意
     * @throws IOException      异常
     * @throws ServletException 异常
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
//        log.info("过滤器开始运行。。。");
//        long id = Thread.currentThread().getId();
//        log.info("线程id为：{}",id);

        //1 先判断是哪个请求
        String requestURI = request.getRequestURI();
//        log.info("拦截到的请求：{}", requestURI);
        //2 定义不需要处理的请求路径 : "/common/**"
        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/user/login",
                "/user/sendMsg"
        };
        //3 判断请求是否需要处理
        boolean check = check(urls, requestURI);
        if (check) {
            // 不需要处理，直接放行
//            log.info("本次请求：{}不需要处理，直接放行", requestURI);
            filterChain.doFilter(request,response);
            return;
        }
        //4.1 客户端登录请求需要处理，那么先判断用户是否登录
        if (request.getSession().getAttribute("employee") != null){
            // 用户已经登录，那么直接放行
            Long empId = (Long) request.getSession().getAttribute("employee");
//            log.info("客户端用户已经登录，id为：{}，直接放行", empId);
            BaseContext.setCurrentId(empId);
            filterChain.doFilter(request,response);
            return;
        }

        //4.2 手机端登录请求，需要处理
        if (request.getSession().getAttribute("user") != null){
            // 用户已经登录，那么直接放行
            Long userId = (Long) request.getSession().getAttribute("user");
            log.info("手机端用户已经登录，id为：{}，直接放行", userId);
            BaseContext.setCurrentId(userId);
            filterChain.doFilter(request,response);
            return;
        }

        //5 用户没有登录，过滤本次请求，返回未登录结果，通过输出流方式向客户端页面响应数据
        log.info("用户未登录");
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
    }

    /**
     * 初始化方法
     */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    /**
     * 销毁方法
     */
    @Override
    public void destroy() {
        Filter.super.destroy();
    }

    /**
     * 路径匹配，检查本次请求是否需要放行
     * @param urls 路径数组
     * @param URI 被检查的路径
     * @return 返回Boolean
     */
    public boolean check(String[] urls,String URI){
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, URI);
            if(match){
                return true;
            }
        }
        return false;
    }
}
